<template>
  <PageWrapper contentFullHeight dense>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <a-button
          type="primary"
          @click="handleSubmit"
          v-if="upLoadShow != '1'"
          :disabled="!shenhetijiao"
          v-hasAnyPermission="['targetYearCommit:commit']"
        >
          审核并提交
        </a-button>
        <BasicUpload2
          :api="importEnrollmentAssement"
          :maxSize="20"
          :maxNumber="1"
          :showPreviewButton="false"
          :accept="['xlsx']"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE }"
          @change="handleChanges"
          v-hasAnyPermission="['taskTarget:importEnrollmentMark']"
        />
        <a-button v-hasAnyPermission="['timeUpload:task']" type="primary" @click="openModal2"
          >设置资料上传截止时间</a-button
        >
        <!-- <a-button type="primary" @click="openModal2"> 设置资料上传截止时间</a-button> -->
        <BasicUpload
          v-hasAnyPermission="['taskTarget:import']"
          :api="uploadFile"
          :maxNumber="1"
          :maxSize="2000"
          :accept="['xlsx']"
          :showPreviewButton="false"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE }"
          @change="handleChange"
          v-if="nextopenes && upLoadShow == '1'"
        />
        <a-button
          color="success"
          @click="oped"
          v-hasAnyPermission="['taskTarget:import']"
          v-if="(importFirst = 'true') && ops && upLoadShow == '1'"
          >重新上传目标任务书</a-button
        >
        <BasicUpload
          :api="uploadFile"
          :maxNumber="1"
          :maxSize="200"
          :showPreviewButton="false"
          :accept="['xlsx']"
          :uploadParams="{ bizType: FileBizTypeEnum.BASE_FILE, sign: 1 }"
          @change="handleChange"
          v-if="nextopen && upLoadShow == '1'"
        />
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action' && record.workType">
          <div class="father-btn">
            <BasicUpload
              :maxSize="200"
              :maxNumber="10"
              @change="handleChanges"
              @click="dianji(record)"
              :api="UploadPdf"
              class="my-5"
              :accept="['pdf']"
              :records="record.id"
              v-if="
                upLoadShow != '1' &&
                !record.isExpiration &&
                record.state &&
                !record.isZhaoshengTarget
              "
            />
            <!-- v-if="upLoadShow != '1' && !record.isExpiration" -->
            <!-- v-hasAnyPermission="['take:openupload']" -->
            <a-button
              v-if="upLoadShow != '1' && record.isExpiration && !record.isZhaoshengTarget"
              type="default"
              :disabled="true"
              >上传时间截止</a-button
            >
            <TableAction
              class="search"
              :actions="[
                {
                  icon: 'ant-design:search-outlined',
                  tooltip: '预览',
                  onClick: handleView.bind(null, record),
                },
              ]"
            />
          </div>
        </template>
      </template>
    </BasicTable>
    <Modal @register="register2" />
    <EditModal @register="registerDrawer" @success="handleSuccess" :foundId="upLoadShow" />
  </PageWrapper>
</template>
<script lang="ts">
  import {
    defineComponent,
    onMounted,
    ref,
    unref,
    // computed,
    // reactive ,
  } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageWrapper } from '/@/components/Page';
  import { TenantStatusEnum } from '/@/enums/biz/tenant';
  import { RoleEnum } from '/@/enums/roleEnum';
  import { FileBizTypeEnum } from '/@/enums/commonEnum';
  import { handleFetchParams } from '/@/utils/lamp/common';
  import { searchFormSchema, columns } from './tenant';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import BasicUpload from './Upload/src/BasicUpload.vue';
  import BasicUpload2 from './Upload/src/BasicUpload2.vue';
  import {
    uploadFile,
    importQimoOr,
    AllList,
    UploadPdf,
    NewUpload,
    checkIsCommit,
    commitConfirm,
    importEnrollmentAssement,
  } from '/@/api/basic/qimo/index';
  import { UploadPdfResult } from '/@/api/basic/qimo/model/index';
  import EditModal from './Edit/Edit.vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useDrawer } from '/@/components/Drawer';
  import { ActionEnum } from '/@/enums/commonEnum';
  import Modal from './Modal.vue';
  import { useModal } from '/@/components/Modal';
  // import { number } from 'vue-types';
  export default defineComponent({
    name: '期末目标',
    components: {
      BasicTable,
      PageWrapper,
      BasicUpload,
      TableAction,
      EditModal,
      Modal,
      BasicUpload2,
    },
    emits: ['change', 'delete', 'preview-delete', 'update:value', 'info'],
    setup() {
      const { t } = useI18n();
      const nextopen = ref(false);
      const nextopenes = ref(false);
      const shenhetijiao = ref(true);
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const upLoadShow = userStore.getTenantId;
      const [register2, { openModal: openPingfen }] = useModal();
      const showSearche: any = userStore.getTenantId;
      let importFirst = 'false';
      const chakan = ref(Boolean);
      const fileList = ref<UploadPdfResult[] | any[]>([]);
      const uploadID = ref();
      const arr = {
        otherId: userStore.getTenantId,
      };
      onMounted(async () => {
        try {
          // const arrs = {
          //   otherId: arr.otherId,
          //   year: new Date().getFullYear(),
          // };
          const response = await importQimoOr(); // 调用接口获取数据
          const checkIsCommits = await checkIsCommit();
          importFirst = String(response);
          shenhetijiao.value = Boolean(checkIsCommits);
          return [importFirst, shenhetijiao];
          // data.value = response.data; // 将接口返回的数据赋值给 data
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      });
      const dataList = ref([]);
      const [registerTable, { expandAll, getDataSource, reload }] = useTable({
        title: '期末目标考核材料详情',
        api: AllList,
        columns,
        dataSource: dataList,
        formConfig: {
          labelWidth: 120,
          schemas: searchFormSchema,
          resetButtonOptions: {
            preIcon: 'ant-design:rest-outlined',
          },
          submitButtonOptions: {
            preIcon: 'ant-design:search-outlined',
          },
        },
        childrenColumnName: 'list',
        clickToRowSelect: false,
        isTreeTable: true,
        beforeFetch: handleFetchParams,
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: false,
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
          columnWidth: 40,
        },
        actionColumn: {
          width: 100,
          title: `预览下载支撑材料`,
          dataIndex: 'action',
        },
      });
      // 编辑页弹窗
      const [registerDrawer, { openDrawer }] = useDrawer();
      let ops = ref(true);
      let apichange = ref(false);
      function oped() {
        createConfirm({
          iconType: 'warning',
          content: '确定要重新上传吗？一旦开启重新上传，之前所做的所有操作将全部失效',
          onOk: async () => {
            nextopen.value = true;
            ops.value = false;
            apichange.value = true;
          },
        });
      }
      function openModal2() {
        openPingfen(true, {
          arr,
        });
      }
      function handleUpload() {
        nextopenes.value = true;
      }
      function onFetchSuccess() {
        // 演示默认展开所有表项
        // nextTick(expandAll);
      }

      // 弹出编辑页面
      function handleView(record: Recordable, e: Event) {
        // 获取表格数据参数
        const vass = getDataSource();
        chakan.value = vass[0].list[0].state;
        e?.stopPropagation();
        openDrawer(true, {
          record,
          type: ActionEnum.VIEW,
          opednext: chakan.value,
        });
      }
      function dianji(record) {
        uploadID.value = record;
      }
      // 新增或编辑成功回调
      function handleSuccess() {
        reload();
      }
      // 上传Pdf
      async function taskInterimMaterial(fileIds) {
        const result = await NewUpload(fileIds);
        return result;
      }
      // 保存最终分数
      // 提交
      async function handleSubmit() {
        const arrs = {
          otherId: arr.otherId,
          year: new Date().getFullYear(),
        };
        // const otherId = getDataSource();
        await commitConfirm(arrs);
        createMessage.success(`评分提交成功`);
        shenhetijiao.value = !shenhetijiao.value;
        reload();
      }
      function handleChanges(files: UploadPdfResult[]) {
        fileList.value = [...unref(fileList), ...(files || [])];
        const newUpload: string[] = [];
        console.log(files);
        for (var i = 0; i < files.length; i++) {
          const list = [files[i].id];
          const StringList = String(list);
          newUpload.push(StringList);
        }

        let targetTwoId = ref();
        if (uploadID.value.twoLevelTargetId) {
          targetTwoId.value = uploadID.value.twoLevelTargetId;
        } else {
          targetTwoId.value = uploadID.value.id;
        }
        const arrs = {
          tenantId: uploadID.value.tenantId,
          fileIds: newUpload,
          targetTwoId: targetTwoId.value,
          remarks: uploadID.value.remarks,
        };

        taskInterimMaterial(arrs);

        // JSON.stringify(params)
        return createMessage.warning(t('component.upload.sessuess'));
      }
      return {
        arr,
        importEnrollmentAssement,
        handleSubmit,
        shenhetijiao,
        register2,
        openModal2,
        handleSuccess,
        UploadPdf,
        registerDrawer,
        chakan,
        handleView,
        dianji,
        registerTable,
        TenantStatusEnum,
        uploadFile,
        FileBizTypeEnum,
        RoleEnum,
        importQimoOr,
        importFirst,
        oped,
        ops,
        upLoadShow,
        nextopen,
        nextopenes,
        handleUpload,
        apichange,
        AllList,
        expandAll,
        onFetchSuccess,
        handleChanges,
        handleChange: () => {
          nextopen.value = false;
          ops.value = true;
          createMessage.success(`文件上传成功`);
        },
      };
    },
  });
</script>
<style>
  .search {
    flex: 1;
  }

  .my-5 {
    flex: 1;
  }

  .father-btn {
    display: flex;
  }

  .foundSome {
    float: right;
  }
</style>
